package com.myCinema.copy;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class ActionMapper {
	private static Map<String,ActionMapping> mapper = new HashMap<String, ActionMapping>();
	static{
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputStream is = ActionMapper.class.getResourceAsStream("/struts.xml");
			Document doc = db.parse(is);
			NodeList nodes = doc.getElementsByTagName("action");
			for (int i = 0; i < nodes.getLength(); i++) {
				Element el = (Element) nodes.item(i);
				String key = el.getAttribute("name");
				String name = el.getAttribute("class");
				ActionMapping am = new ActionMapping();
				am.setName(key);
				am.setClassName(name);
				mapper.put(key, am);
				NodeList subNodes = el.getElementsByTagName("result");
				for(int j = 0 ; j< subNodes.getLength() ; j++){
					Element subEl = (Element) subNodes.item(j);
					String rname = subEl.getAttribute("name");
					String type = subEl.getAttribute("type");
					String url = subEl.getTextContent();
					Result r = new Result(rname, type, url);
					am.mapping.put(rname, r);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static ActionMapping createActionMapping(String name){
		return mapper.get(name);
	}
	
	public static void main(String[] args) {
		for(String key : mapper.keySet()){
			System.out.println(key);
			ActionMapping am = mapper.get(key);
			for(String name : am.getMapping().keySet()){
				Result r = am.getMapping().get(name);
				System.out.print(r.getType()+","+r.getUrl()+","+r.getName());
			}
		}
	}
}
